package com.jianqiao.delivery.pay.service.impl;

import com.jianqiao.delivery.pay.service.SripeVisaService;
import com.ruoyi.common.utils.DateUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.stripe.Stripe;
import com.stripe.exception.StripeException;
import com.stripe.model.Customer;
import com.stripe.model.PaymentIntent;
import com.stripe.param.CustomerCreateParams;
import com.stripe.param.PaymentIntentCreateParams;
//import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
//import org.nft.common.core.utils.DateUtils;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.UUID;

/**
 * author: cyx
 * create: 2024/11/25 11:33
 **/
@Slf4j
@Service
public class SripeVisaServiceImpl implements SripeVisaService {
    @Override
    public String createOrder() {
        // 用户名
        String userName = "jianqiao";
        // 邮箱
        String email = "ptjqtd@qq.com";
        // 注册时间
        String registerTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, new Date());
        PaymentIntent paymentIntent;
        try {
            Stripe.apiKey = "sk_test_51QOFD0GHHdqnF7aG90TdkTGPkTlonPsHy1pMUjznZmsdrilkH2frUVPCUKoMs1BDxJFGPxdxrsEwLqn4znc0IOa800jzIM7aSi";
            // 创建客户信息
            CustomerCreateParams customerParams = CustomerCreateParams.builder()
                    .setName(userName)
                    .setEmail(email)
                    .setDescription("用户注册时间：" + registerTime).build();
            Customer customer = Customer.create(customerParams);
            // 客户id
            String customerId = customer.getId();
            // 创建支付订单
            PaymentIntentCreateParams params = PaymentIntentCreateParams.builder()
                    // 支付金额
                    .setAmount(100L)
                    // 货币类型 美元 usd 港币 hkd
                    .setCurrency("usd")
                    // 支付方式 card 信用卡或借记卡支付 alipay：支付宝支付，适用于中国地区的用户 wechat_pay：微信支付，适用于中国地区的用户
                    .addPaymentMethodType("card")
                    // 存储自定义数据的属性
                    .putMetadata("orderId", UUID.randomUUID().toString().replace("-", ""))
                    // 客户id
                    .setCustomer(customerId)
                    // 描述
                    .setDescription("测试购买商品").build();
            paymentIntent = PaymentIntent.create(params);
            System.out.println("visa卡支付下单返回结果：" + paymentIntent);
        } catch (StripeException e) {
            System.out.println("visa卡支付下单异常：" + e.getMessage());
            throw new RuntimeException(e);
        }
        // 前端根据客户端密钥发起支付
        return paymentIntent.getClientSecret();
    }

    @Override
    public void stripeEvents(HttpServletRequest request) {
        log.info("进入visa卡监听事件.....");
        try {
            InputStream inputStream = request.getInputStream();
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024 * 4];
            int n = 0;
            while (-1 != (n = inputStream.read(buffer))) {
                output.write(buffer, 0, n);
            }
            String payload = output.toString(StandardCharsets.UTF_8);
            JSONObject jsonObject = JSONObject.parseObject(payload);
            // 事件类型
            String type = jsonObject.getString("type");
            // 订单id
            String orderId = jsonObject.getJSONObject("data").getJSONObject("object").getJSONObject("metadata").getString("orderId");
            // 支付完成/支付成功
            if ("checkout.session.completed".equals(type) || "payment_intent.succeeded".equals(type)) {
                // TODO 根据订单id修改状态->支付成功

            }
        } catch (Exception e) {
            log.info("stripe异步通知（webhook事件）异常：{}", e.getMessage());
        }
    }

    @Override
    public void retrieve(String payId) {
        try {
            Stripe.apiKey = "****************";
            PaymentIntent paymentIntent = PaymentIntent.retrieve(payId);
            paymentIntent.cancel();
            log.info("取消stripe平台付款记录成功,付款id：{}", payId);
        } catch (StripeException e) {
            log.error("取消stripe平台付款记录异常：{}", e.getMessage());
            throw new RuntimeException(e);
        }
    }
}
